<template>
  <!--编辑商品资料-->
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogVisible"
    :beforeClose = 'handleClose'
    width="700px">
    <div style="margin-top:-30px">
      <el-form size="mini" :model="sendForm" label-width="100px"  ref="sendForm" :rules="rules">
        <el-divider>基础信息（必填）</el-divider>
        <el-row>
           <el-col :span="12">
             <el-form-item label="产品大类：" prop="parentCategoryId">
               <el-select filterable v-model="sendForm.parentCategoryId" @change="changeClass" :disabled="sendForm.goodsSnId ? true : false">
                  <el-option :value="item.categoryId" :label="item.categoryName" v-for="item in classList" :key="item.categoryId"></el-option>
               </el-select>
             </el-form-item>
           </el-col>
            <el-col :span="12">
              <el-form-item label="产品小类：" prop="categoryId" >
                <el-select filterable v-model="sendForm.categoryId" @change="changeSubClass" :disabled="sendForm.goodsSnId ? true : false">
                   <el-option :value="item.categoryId" :label="item.categoryName" v-for="item in subClassList" :key="item.categoryId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产厂家：" prop="brandName">
                <el-select filterable clearable v-model="sendForm.brandName" :disabled="sendForm.goodsSnId ? true : false">
                  <el-option :value="item.brandName" :label="item.brandName" v-for="item in brandList" :key="item.brandName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
             <el-form-item label="牌号规格：" prop="goodsSn">
               <el-input style="width:193px" clearable v-model="sendForm.goodsSn" :disabled="sendForm.goodsSnId ? true : false"></el-input>
             </el-form-item>
            </el-col>
        </el-row>
        <el-divider>备注信息(选填，填写后会以【/内容】追加到牌号规格后)</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="包装规格：">
              <el-select clearable v-model="sendForm.packSize" :disabled="sendForm.goodsSnId ? true : false">
                <el-option value="大包" label="大包"></el-option>
                <el-option value="小包" label="小包"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品粘度：">
              <el-select clearable v-model="sendForm.productViscosity" :disabled="sendForm.goodsSnId ? true : false">
                <el-option value="低粘" label="低粘"></el-option>
                <el-option value="中粘" label="中粘"></el-option>
                <el-option value="高粘" label="高粘"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品光泽：">
              <el-select clearable v-model="sendForm.productGloss" :disabled="sendForm.goodsSnId ? true : false">
                <el-option value="有光" label="有光"></el-option>
                <el-option value="半光" label="半光"></el-option>
                <el-option value="消光" label="消光"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品颜色：">
              <el-input style="width:193px" v-model="sendForm.productColor" clearable :maxlength="10" :disabled="sendForm.goodsSnId ? true : false"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产产线：">
              <el-input style="width:193px" v-model="sendForm.productLine" clearable :maxlength="10" :disabled="sendForm.goodsSnId ? true : false"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>其他信息(部分必填)</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否主营：" prop="isSelfSale">
              <el-select clearable v-model="sendForm.isSelfSale">
                <el-option :value="1" label="主营"></el-option>
                <el-option :value="0" label="非主营"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人："  prop="chargeUserId">
              <el-select v-model="sendForm.chargeUserId" filterable clearable>
                <el-option v-for="item in salesmanLists" :key="item.userId" :value="item.userId" :label="item.userName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="协助人：" >
              <el-select v-model="sendForm.assistUserId" filterable clearable>
                <el-option v-for="item in salesmanLists" :key="item.userId" :value="item.userId" :label="item.userName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总负责人："  prop="lastUserId">
              <el-select v-model="sendForm.lastUserId" filterable clearable >
                <el-option v-for="item in salesmanLists" :key="item.userId" :value="item.userId" :label="item.userName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最低毛利：" >
              <el-input clearable style="width:193px;"  v-model="sendForm.minProfit" type="number"></el-input><span style="font-size:12px;padding-left:5px;color:#888">元/吨</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指导毛利：" >
              <el-input clearable style="width:193px;" v-model="sendForm.normProfit" type="number"></el-input><span style="font-size:12px;padding-left:5px;color:#888">元/吨</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售卖包装：" prop="goodsWeight">
              <el-input clearable style="width:193px;" v-model="sendForm.goodsWeight" type="number"></el-input><span style="font-size:12px;padding-left:5px;color:red">吨/包</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起订数量：" prop="buyMinNum">
              <el-input clearable style="width:193px;" v-model="sendForm.buyMinNum" type="number"></el-input><span style="font-size:12px;padding-left:5px;color:red">吨</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确认</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {materialEdit,goodsGroupList,materialClassTree,materialBrandList} from '@/api/allInLine/goods'
import {getOrderUsersList} from '@/api/partner'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui';
const defaultSendForm={
  "goodsSnId": 0, //物料ID
  "parentCategoryId": "", //一级分类ID
  "parentCategoryName": "", //一级分类名称
  "categoryId": "", //二级分类ID
  "categoryName": "", //二级分类名称
  "brandName": "", //厂家
  "goodsSn": "", //牌号
  "packSize": "", //包装规格
  "productLine": "", //生产产线
  "productViscosity": "", //产品粘度
  "productGloss": "", //产品光泽
  "productColor": "", //产品颜色
  "isSelfSale": "", //是否主营，0-否，1-是
  "chargeUserId": "", //负责人
  "assistUserId": "", //协助人
  "lastUserId": "", //总负责人
  "minProfit": 50, //最低毛利
  "normProfit": 100, //指导毛利
  "goodsWeight": "", //售卖包装
  "buyMinNum": "", //起订数量
};

export default {
  name: "index",
  data() {
    const validateGoodsWeight = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('数量不能小于0吨'))
      }
      callback()
    };
    const validateGoodsNum = (rule, value, callback) => {
      let step = (parseInt((value*1e5).toFixed(0))) % (parseInt((this.sendForm.goodsWeight*1e5).toFixed(0)))
      if(!value && value !== 0){
        callback(new Error('此项必填'))
      } else if(step != 0){
        callback(new Error('请按包装的倍数输入起订数量'))
      } else{
        callback()
      }
    };
    return {
      goodSortList:[],
      salesmanLists:[],
      dialogVisible:false,
      btnLoading:false,
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
      rules: {
        parentCategoryId: [
          { required: true, message: '此项必填', trigger: 'change' }
        ],
        categoryId: [
          { required: true, message: '此项必填', trigger: 'change' }
        ],
        brandName: [
          { required: true, message: '此项必填', trigger: 'change' }
        ],
        goodsSn: [
          { required: true, message: '此项必填', trigger: 'blur' }
        ],
        isSelfSale: [
          { required: true, message: '此项必填', trigger: 'change' }
        ],
        chargeUserId: [
          { required: true, message: '此项必填', trigger: 'change' }
        ],
        goodsWeight: [
          { required: true, message: '此项必填', trigger: 'blur' },
          {validator:validateGoodsWeight,trigger: "blur"}
        ],
        buyMinNum: [
          {required: true,validator:validateGoodsNum,trigger: "blur"}
        ],
        lastUserId: [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
      },
      options:[],
      title:'',
      goodsSnList:[],
      gxSnList:[],
      classList:[],
      subClassList:[],
      brandList:[]
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {

  },
  created() {
    // this.getSortList()
  },
  filters: {

  },
  methods:{

    //切换小类
    changeSubClass(){
      let i = this.subClassList.findIndex((el)=>{
        return el.categoryId == this.sendForm.categoryId
      })
      if(i!=-1){
        this.sendForm.categoryName = this.subClassList[i]['categoryName']
      }
    },

    //获取厂家
    getBrandList(){
      materialBrandList({keywords:''}).then((res)=>{
        this.brandList = res
      })
    },
    //获取大类
    getClassList(){
      return materialClassTree({categoryName:''}).then((res)=>{
        this.classList = res
      })
    },
    //切换大类
    changeClass(){
      let i = this.classList.findIndex((el)=>{
        return el.categoryId == this.sendForm.parentCategoryId
      })
      if(i != -1){
        this.subClassList = this.classList[i]['children']
        this.sendForm.parentCategoryName = this.classList[i]['categoryName']
      }
      this.sendForm.categoryId = '';
      this.sendForm.categoryName = ''
    },
    // 获取商品分类
    getSortList() {
      goodsGroupList().then(res=>{
      this.goodSortList=res
    })
    },

    //显示
    showPop(item){
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm))
      if (item) {
        this.dialogVisible = true;
        this.title = '编辑物料'
        for (let key in defaultSendForm) {
          this.sendForm[key] = item[key] || item[key] == 0 ? item[key] : defaultSendForm[key];
        }
      }else{
        this.title = '新增物料'
        this.sendForm.materialId = 0
        this.dialogVisible = true;
      }
      this.getClassList().then(()=>{
         if(this.sendForm.parentCategoryId){
           let i = this.classList.findIndex((el)=>{
             return el.parentCategoryId == this.sendForm.parentCategoryId
           })
           if(i != -1){
             this.subClassList = this.classList[i]['children']
           }
         }
      })
      this.getBrandList()
      this.getSalesmanList()
    },

    //关闭
    handleClose(){
      this.dialogVisible = false;
      this.$refs.sendForm.resetFields();
    },
    // 可筛选销售员
    getSalesmanList(){
      getOrderUsersList().then(res=>{
        this.salesmanLists=res
      })
    },
    //确认
    handleConfirm(){
       const data = JSON.parse(JSON.stringify(this.sendForm))
       this.$refs.sendForm.validate(volid=>{
        if(volid){
          this.btnLoading =true
          materialEdit(data).then(res=>{
          Message.success('提交物料成功')
          this.btnLoading =false
          this.dialogVisible = false;
          this.$emit('update')
          }).catch(err=>{
            this.btnLoading =false
          })
        }
      })
    },
  },
}
</script>

<style  lang="scss">
.el-divider__text.is-center{
  white-space: nowrap;
}
</style>
